package cool.taomu.toolkit.apilog

import com.google.auto.service.AutoService
import com.google.common.eventbus.AsyncEventBus
import com.google.inject.AbstractModule
import com.google.inject.matcher.Matchers
import cool.taomu.toolkit.TaomuConfigure
import cool.taomu.toolkit.TaomuGuice
import cool.taomu.toolkit.matcher.PackageMatcher
import cool.taomu.toolkit.platform.inter.AbsPlatform
import cool.taomu.toolkit.platform.inter.IPlatform
import cool.taomu.toolkit.provider.AsyncEventBusProvider
import cool.taomu.toolkit.utils.ReflectionsScanner
import javax.ws.rs.Path
import org.slf4j.LoggerFactory
import java.util.ArrayList
import com.google.inject.Key
import com.google.inject.name.Names

@AutoService(IPlatform)
class ApiLogPlugin extends AbsPlatform {
    val static LOG = LoggerFactory.getLogger(ApiLogPlugin)

    override note() {
        "API LOG 插件"
    }

    override packages() {
    }

    override module(TaomuConfigure config) {
        new AbstractModule() {
            override configure() {
                if (config.isExist("taomu.apilog.name")) {
                    TaomuGuice.binder(binder(), AsyncEventBus).toProvider(AsyncEventBusProvider).asEagerSingleton
                    val list = new ArrayList<String>();
                    config.binder("taomu.apilog.package", [
                        if (it instanceof String) {
                            list.add(it)
                        }
                    ])

                    var after = new ApiLogInterceptor();
                    requestInjection(after);
                    bind(ApiLogHandler).asEagerSingleton
                    var pm = new PackageMatcher(list)
                    bindInterceptor(
                        pm,
                        Matchers.annotatedWith(Path),
                        after
                    );
                    var set = ReflectionsScanner.scanType(Path, "cool.taomu")
                    set.forEach [
                        bind(it)
                    ]
                }
            }
        }
    }

    override start() {
    }

    override init() {
        if (this.context.isExistingBinding(String, "taomu.apilog.name")) {
            LOG.info("注册ApiLogHandler")
            var eventbus = this.context.getInstance(AsyncEventBus) as AsyncEventBus;
            eventbus.register(this.context.getInstance(ApiLogHandler))
        }
    }

}
